import Taro from '@tarojs/taro';
import { sleep } from '.';

// 蓝牙权限信息（后期如果微信开发更多字段，在这里实现更多字段来判断）
interface IBlePremissionInfo {
  miniHasBlePermission?: boolean; // 小程序是否有授权
  wechatAppHasBlePermission?: boolean; // 微信app是否有权限（整合的字段，包括蓝牙权限，位置权限等）
}

export interface IBleCanUseProps {
  enabled: boolean; // 蓝牙是否可用，不可用的话，具体错误看errorInfo
  errorInfo?: IBlePremissionInfo;
}

/**
 * 判断当前设备是否打开蓝牙
 */
function isBleCanUse(): Promise<IBleCanUseProps> {
  return new Promise(async (resolve) => {
    
    const res = await wx.getSystemInfo();
    console.debug('getSystemInfo', res)
    let enabledData = {
      bleEnabled: res.bluetoothEnabled,
      locationEnabled: true
    }
    if (res.platform === 'android') {
      enabledData.bleEnabled = res.bluetoothEnabled && res.bluetoothAuthorized;
    }
    if (res.platform === 'android') {
      enabledData.locationEnabled = res.locationEnabled
    }
    if (enabledData.locationEnabled && enabledData.bleEnabled) {
      resolve({ enabled: true });
    } else {
      resolve({ enabled: false, ...enabledData, errorInfo: { wechatAppHasBlePermission: false } });
    }
  });
}

// 查询小程序是否有蓝牙授权
function queryMiniHasBlePermission(): Promise<IResult> {
  return new Promise(resolve => {
    Taro.getSetting({
      success(res) {
        console.log('queryMiniHasBlePermission res', res);
        const { authSetting } = res;
        resolve({ success: true, data: { miniHasBlePermission: authSetting['scope.bluetoothBackground'] } });
      },
      fail(res) {
        resolve({ success: false, message: res.errMsg });
      },
    });
  });
}

// 查询微信app是否有蓝牙权限，蓝牙开关，定位权限，地理位置的系统开关
async function queryWechatAppHasBlePermission() {
  const res = await Taro.getSystemInfoAsync();
  // Taro.getSetting() // 蓝牙授权（iOS）
  return {
    platform: res.platform,
    locationAuthorized: res.locationAuthorized,
    bluetoothEnabled: res.bluetoothEnabled,
    locationEnabled: res.locationEnabled,
  }

}

export { isBleCanUse };
